#!/bin/sh

template() {
	artifacts=$(echo "$1" | head -n1 | cut -d ';' -f1)
	toy=$(echo "$1" | head -n1 | cut -d ';' -f2)
	item=$(echo "$1" | head -n1 | cut -d ';' -f3)
	status=$(echo "$1" | head -n1 | cut -d ';' -f4)
	content1=$(echo "$1" | head -n1 | cut -d ';' -f5-)
	content2=$(echo "$1" | tail -n+2)

	content=$(printf '%s\n%s\n' "$content1" "$content2" | sed -E 's/ ([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}.[0-9]{9}\+[0-9]{2}:[0-9]{2})/\n\1/g')

	cat <<EOF
<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<meta name="viewport" content="width=device-width, initial-scale=1.0">
EOF
	printf '\t\t<title>toymaker::%s/%s</title>\n' "$toy" "$item"
	cat <<EOF
		<style>
			* {
				box-sizing: border-box;
			}
			a {
				color: #00afff;
			}
			a:hover {
				background-color: #db9d3b;
				color: #000000;
			}
		</style>
	</head>
	<body style="background-color: #292929; color: #fafafa;">
		<header style="font-size: 1.25rem; padding-top: .3125rem; padding-bottom: .3125rem;">
			<a href="/toys/" style="font-family: monospace; text-decoration: none;">toymaker</a>
		</header>
		<main style="margin-left: 1rem; margin-top: 2rem;">
EOF
	printf '\t\t\t<h1><a href="/toys/%s">%s</a>/%s</h1>\n' "$toy" "$toy" "$item"
	if [ "$status" = '0' ]
	then
		printf '\t\t\t<h2 style="color: #5af78e;">OK</h2>\n'
	elif [ "$status" = 'r' ]
	then
		printf '\t\t\t<h2>Running</h2>\n'
	else
		printf '\t\t\t<h2 style="color: #ff5c57;">Error</h2>\n'
	fi

	if [ -n "$artifacts" ]
	then
		printf '\t\t\t<details>\n'
		printf '\t\t\t\t<summary style="cursor: pointer;">artifacts</summary>\n'
		printf '\t\t\t\t<ul>\n'
		for artifact in $artifacts
		do
			printf '\t\t\t\t\t<li><a href="/toys/%s/%s/%s">%s</a></li>\n' "$toy" "$item" "$artifact" "$artifact"
		done
		printf '\t\t\t</details>'
	fi

	printf '\t\t\t<code><pre style="border: 1px #aaa solid; padding: 1rem; overflow: scroll; color: #cdb360;">\n'
	printf '%s' "$content"
	printf '\t\t\t</pre></code>\n'
	cat <<EOF
		</main>
	</body>
</html>
EOF
}
